package com.mhc.suzuki.service.impl;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.CreditQueryApplyBO;
import com.mhc.suzuki.bo.CustomerBO;
import com.mhc.suzuki.constant.*;
import com.mhc.suzuki.dal.mapper.ext.CreditQueryApplyExtMapper;
import com.mhc.suzuki.dal.mapper.ext.OrderCustomerRelExtMapper;
import com.mhc.suzuki.dal.model.CreditQueryApplyDO;
import com.mhc.suzuki.dal.model.CustomerDO;
import com.mhc.suzuki.dal.model.OrderCustomerRelDO;
import com.mhc.suzuki.dal.model.OrderDO;
import com.mhc.suzuki.dal.query.CreditQueryApplyQuery;
import com.mhc.suzuki.dal.query.OrderCustomerRelQuery;
import com.mhc.suzuki.dal.query.OrderQuery;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.CreditQueryApplyManager;
import com.mhc.suzuki.manager.CustomerManager;
import com.mhc.suzuki.manager.OrderCustomerRelManager;
import com.mhc.suzuki.manager.OrderManager;
import com.mhc.suzuki.service.ApplyService;
import com.mhc.suzuki.service.CreditSerivce;
import com.mhc.suzuki.service.MessageService;
import com.mhc.suzuki.service.OrderService;
import com.subaru.common.query.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 征信列表查询、征信结果录入、征信详情查询
 * Created by HMJ on 2017/8/19.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CreditSerivceImpl implements CreditSerivce {

    @Autowired
    private CreditQueryApplyExtMapper creditQueryApplyExtMapper;
    @Autowired
    private CreditQueryApplyManager creditQueryApplyManager;
    @Autowired
    private CustomerManager customerManager;
    @Autowired
    private OrderCustomerRelManager orderCustomerRelManager;
    @Autowired
    private OrderCustomerRelExtMapper orderCustomerRelExtMapper;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private SubmitTaskServiceImpl submitTaskServiceImpl;
    @Autowired
    private OrderServiceImpl orderServiceImpl;
    @Autowired
    private OrderService orderService;

    /**
     * 获取查询征信列表
     * @param creditQueryApplyBO    //表单搜索内容
     * @param logedUser             //登录人信息
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public PageResult<CreditQueryApplyBO> selectByCreidtList(CreditQueryApplyBO creditQueryApplyBO,User logedUser) throws SuzukiCommonException {
        log.info("开始查询征信列表...");
        Map<String, Object> paramMap = new HashMap<>(64);
        paramMap.put("keyword", creditQueryApplyBO.getKeyword());             //关键字
        paramMap.put("staffId", creditQueryApplyBO.getStaffId());             //员工编号
        paramMap.put("deptId", creditQueryApplyBO.getDeptId());               //部门编号
        paramMap.put("gmtStart", creditQueryApplyBO.getGmtStart());           //申请起始时间
        paramMap.put("gmtEnd", creditQueryApplyBO.getGmtEnd());               //申请结束时间
        paramMap.put("pageSize", creditQueryApplyBO.getPageSize());           //每页大小
        paramMap.put("isDeleted", IsDeletedEnum.NORMAL.getCode());       //未删除
        paramMap.put("bankId", logedUser.getBankId());                        //驻点员银行ID
        paramMap.put("orderStatusList", creditQueryApplyBO.getStatusList());  //订单状态列表
        paramMap.put("customerType", CustomerTypeEnum.BUYER.getCode());       //客户在当前订单中的角色
        /**计算pageOffset**/
        CreditQueryApplyQuery query = new CreditQueryApplyQuery();
        query.setPageNo(creditQueryApplyBO.getPageNo());
        query.setPageSize(creditQueryApplyBO.getPageSize());
        paramMap.put("pageOffset",query.getPageOffset());           //开始查询位
        /**通过搜索条件查询主贷人的征信列表**/
        List<CreditQueryApplyBO> creditList =  creditQueryApplyExtMapper.selectByCreditList(paramMap);
        /**查询总条数**/
        int count = creditQueryApplyExtMapper.countByCreditList(paramMap);
        log.info("征信条数为：{}条", count);
        /**组装返回信息**/
        PageResult<CreditQueryApplyBO> result = new PageResult<>();
        result.setPageNo(creditQueryApplyBO.getPageNo());
        result.setPageSize(creditQueryApplyBO.getPageSize());
        result.setTotalCount(count);
        result.setResult(creditList);
        return result;
    }

    /**
     * 根据订单号获取征信结果详情
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public List<CreditQueryApplyBO> queryByCreidtInfo(String orderNo) throws SuzukiCommonException{
        log.info("开始查询征信结果详情...");
        /**根据订单号查询征信信息**/
        log.info("正在查询征信信息...");
        List<CreditQueryApplyBO> creditInfoList = creditQueryApplyExtMapper.selectByCreditInfo(orderNo);
        if(!creditInfoList.isEmpty()){
            /**循环征信列表查询客户对应的附件信息**/
            for(CreditQueryApplyBO creditQueryApplyBO:creditInfoList){
                /**将婚姻状态增加汉化字段**/
                if(creditQueryApplyBO.getBemarried()!=null){
                    String beMarriedName = BeMarriedEnum.getBeMarriedEnum(creditQueryApplyBO.getBemarried()).getName();
                    creditQueryApplyBO.setBemarriedName(beMarriedName);
                }
            }
            return creditInfoList;
        }
        throw new SuzukiCommonException(ErrorCodeEnum.SELECT_FAILURE);

    }

    /**
     * 征信结果录入
     * @param creditQueryApplyBO
     * @param logedUser
     * @return
     * @throws SuzukiCommonException
     * @throws IOException
     */
    @Override
    public Boolean saveCreditResult(CreditQueryApplyBO creditQueryApplyBO,User logedUser) throws SuzukiCommonException,IOException {
        log.info("开始录入征信结果...");
        CreditQueryApplyDO creditQueryApplyRecord = new CreditQueryApplyDO();
        /**获取录入征信结果集合**/
        List<Map> resultArr = creditQueryApplyBO.getResultArr();
        if(!resultArr.isEmpty()){
            for (int i = 0; i < resultArr.size(); i++) {
                Map<String,Object> map = resultArr.get(i);
                String id = map.get("creditQueryApplyId").toString();
                String creditResult = map.get("creditResult").toString();
                creditQueryApplyRecord.setCreditQueryApplyId(Long.parseLong(id));          //征信编号
                creditQueryApplyRecord.setCreditResult(creditResult);                      //征信结果
                creditQueryApplyRecord.setHandleStaffId(logedUser.getStaffId());           //征信结果录入员工ID
                creditQueryApplyRecord.setHandleStaffName(logedUser.getStaffName());       //征信结果录入员工姓名
                creditQueryApplyRecord.setQueryStatus(CreditStatusEnum.ENTERED.getCode()); //征信状态
                creditQueryApplyRecord.setRecordTime(LocalDateTime.now());                 //录入时间
                /**根据征信编号和征信结果录入信息**/
                creditQueryApplyManager.updateByPrimaryKeySelective(creditQueryApplyRecord);
            }
            /**录入结束后修改订单状态**/
            int orderStatus = orderService.selectOrderStatus(creditQueryApplyBO.getOrderNo());
            if(orderStatus == OrderStatusEnum.CREDITING.getCode()){
                orderService.changeOrderStatus(creditQueryApplyBO.getOrderNo(),OrderStatusEnum.CREDIT_HAS_BEEN_RECORDER.getCode()); //订单状态改为征信结果已录入
            }else {
                orderService.changeOrderStatus(creditQueryApplyBO.getOrderNo(),OrderStatusEnum.UPDATE_HAS_BEEN_RECORDER.getCode()); //订单状态改为修改征信结果已录入
            }
            //征信录入消息发送
            messageService.sendCreditMessage(creditQueryApplyBO.getOrderNo());
            return true;
        }
        throw new SuzukiCommonException(ErrorCodeEnum.PARAM_ERROR);
    }


    /**
     * 修改征信
     * @param buyerBO         主贷人信息
     * @param commonBuyerBO   共同购车人信息
     * @param sponsorList     担保人信息
     * @return
     * @throws SuzukiCommonException
     * @throws IOException
     */
    @Override
    public Boolean updateCreditInfo(CustomerBO  buyerBO,CustomerBO commonBuyerBO, List<CustomerBO> sponsorList,User logedUser) throws SuzukiCommonException,IOException {
        log.info("开始修改征信信息...");
        /**先判断是否更换了贷款银行**/
        log.info("查询主贷人征信银行...");
        String orderNo = buyerBO.getOrderNo();   //获取订单号
        Long bankId = buyerBO.getBankId();     //获取修改后征信银行ID
        String bankName = buyerBO.getBankName(); ////获取修改后征信银行名称
        /**根据订单号查询修改前的征信银行**/
        OrderDO orderInfo = orderManager.selectByOrderNo(orderNo);
        if(orderInfo!= null){
            Long creditBankId = orderInfo.getLoanBankId();     //获取修改前征信银行
            /**若修改后征信银行与修改前不同**/
            if(!bankId.equals(creditBankId)){
                log.info("已修改了贷款银行，请重新发起征信");
                /**1、将该订单下的所有征信申请记录置---已删除**/
                log.info("开始清理订单为：{}下所有的客户征信关系记录...", orderNo);
                orderCustomerRelExtMapper.updateDeletedByOrderNo(orderNo);
                log.info("清理完成...");
                /**2、修改订单中的贷款银行**/
                log.info("开始更换订单中贷款银行...");
                OrderDO record = new OrderDO();
                OrderQuery query = new OrderQuery();
                record.setLoanBankId(bankId);       //贷款银行ID
                record.setLoanBankName(bankName);   //贷款银行名称
                query.createCriteria().andOrderNoEqualTo(orderNo);   //订单号
                orderManager.updateByQuerySelective(record,query);
                log.info("更换贷款银行完成...");
                /**3、循环插入各类客户的数据**/
                log.info("正在新增主贷人信息...");
                this.saveCustomerInfo(buyerBO,logedUser);
                log.info("新增主贷人信息完成...");
                /**判断是否存在共同购车人**/
                if(!(commonBuyerBO.equals(new CustomerBO()))){
                    log.info("存在共同购车人，正在新增共同购车人信息...");
                    this.saveCustomerInfo(commonBuyerBO,logedUser);
                    log.info("新增共同购车人信息完成...");
                }
                /**判断是否存在担保人**/
                if(!sponsorList.isEmpty()){
                    log.info("存在担保人，正在新增担保人信息...");
                    for(CustomerBO customerBO : sponsorList){
                        this.saveCustomerInfo(customerBO,logedUser);
                    }
                    log.info("新增担保人信息完成...");
                }
            }else {
                log.info("未更改贷款银行...");
                /**若修改后征信银行与修改前相同**/
                /**1、判断是否修改了婚姻状态**/
                log.info("正在查询主贷婚姻状态...");
                Long customerId = buyerBO.getCustomerId();   //获取主贷人的客户编号
                int bemarried = buyerBO.getBemarried();      //获取主贷人修改后的婚姻状态
                /**查询主贷人的信息**/
                CustomerDO customerInfo = customerManager.selectByPrimaryKey(customerId);
                if(customerInfo!= null){
                    int creditBemarried = customerInfo.getBemarried();    //获取修改前的婚姻状态
                    /**若修改后婚姻状态与修改前不同**/
                    if(bemarried!=creditBemarried){
                        log.info("婚姻状态已修改...");
                        /**1、修改客户的婚姻状态**/
                        log.info("正在修改客户婚姻状态...");
                        CustomerDO customerRecord =new CustomerDO();
                        customerRecord.setBemarried(bemarried);      //婚姻状态
                        customerRecord.setCustomerId(customerId);    //客户编号
                        customerManager.updateByPrimaryKeySelective(customerRecord);
                        log.info("修改完成...");
                        log.info("检测当前婚姻状态中...");
                        boolean isMarriedAfter = BeMarriedEnum.isBeMarriedEnum(bemarried);    //修改后婚姻状态
                        boolean isMarriedBefore = BeMarriedEnum.isBeMarriedEnum(creditBemarried);    //修改前婚姻状态
                        if(isMarriedAfter && !isMarriedBefore){
                            /**若原先状态为未婚，则新增共同购车人**/
                            log.info("原状态为未婚，现改为已婚，正在新增共同购车人...");
                            this.saveCustomerInfo(commonBuyerBO,logedUser);
                            log.info("完成新增共同购车人...");
                        }else if(!isMarriedAfter && isMarriedBefore){
                            /**若原先状态为已婚，则删除共同购车人**/
                            log.info("原状态为已婚，现改为未婚，正在删除共同购车人...");
                            OrderCustomerRelQuery query = new OrderCustomerRelQuery();
                            OrderCustomerRelDO record = new OrderCustomerRelDO();
                            query.createCriteria().andOrderNoEqualTo(buyerBO.getOrderNo())       //订单号
                                    .andCustomerTypeEqualTo(CustomerTypeEnum.COMMONBUYER.getCode());  //客户类型
                            record.setIsDeleted(IsDeletedEnum.DELETED.getCode());                //已删除
                            orderCustomerRelManager.updateByQuerySelective(record, query);
                            log.info("删除成功...");
                        }
                    }else {
                        log.info("未修改婚姻状态...");
                    }
                }else{
                    log.info("查询主贷人个人信息异常，请重试...");
                    throw new SuzukiCommonException(ErrorCodeEnum.SELECT_FAILURE);
                }
                /**判断是否新增了担保人**/
                /**1、查询修改前所附带的担保人信息**/
                log.info("正在对比担保人信息...");
                /**获取购车人的担保人列表**/
                Map<String, Object> paramMap = new HashMap<>(64);
                paramMap.put("orderNo", orderNo);
                paramMap.put("isDeleted", IsDeletedEnum.NORMAL.getCode());       //未删除
                paramMap.put("customerType",CustomerTypeEnum.SPONSOR.getCode());      //客户类型：担保人
                List<CustomerBO> oldSponsorrList = orderCustomerRelExtMapper.selectByCustomerList(paramMap);

                for(int i = 0;i<sponsorList.size();i++){
                    boolean isExist = true;        //不存在
                    String cusIdCrad = sponsorList.get(i).getIdCard();   //获取新增担保人身份证号
                    for(int j =0 ;j<oldSponsorrList.size();j++){
                        String oldCusIdCrad = oldSponsorrList.get(j).getIdCard();   //获取原担保人身份证号
                        if(oldCusIdCrad.equals(cusIdCrad)) {
                            isExist = false;      //存在
                            break;
                        }
                    }
                    if(isExist){
                        log.info("存在新担保人信息，正在新增中...");
                        this.saveCustomerInfo(sponsorList.get(i),logedUser);
                    }else{
                        log.info("未存在新担保人信息...");
                    }
                }
                log.info("完成新增担保人...");
            }
            /**修改征信状态**/
            this.updateStatusByOrder(orderNo,logedUser);
        }else {
            log.info("查询主贷人征信信息异常，请重试...");
            throw new SuzukiCommonException(ErrorCodeEnum.SELECT_FAILURE);
        }
        return true;
    }


    /**
     * 新增客户所有信息功能（包括共同购车人、担保人，用于征信修改）
     * @param customerBO
     * @param logedUser
     * @throws SuzukiCommonException
     */
    public void saveCustomerInfo(CustomerBO customerBO,User logedUser) throws SuzukiCommonException{
        /**1、新增客户信息**/
        CustomerDO customerRecord = new CustomerDO();
        if(customerBO.getCustomerId()== null){
            log.info("正在新增客户信息...");
            customerRecord.setCustomerName(customerBO.getCustomerName());                  //客户姓名
            customerRecord.setIdCard(customerBO.getIdCard());                              //身份证号码
            customerRecord.setCompanyNo(logedUser.getCompanyNo());                                              //公司编号
            customerRecord.setStaffId(logedUser.getStaffId());                                                 //客户信息录入人员ID
            customerManager.insertSelective(customerRecord);
            log.info("新增客户信息完成...");
            customerBO.setCustomerId(customerRecord.getCustomerId());
        }
        /**2、新增客户征信信息**/
        log.info("正在新增客户征信信息...");
        CreditQueryApplyDO creditRecord = new CreditQueryApplyDO();
        creditRecord.setCustomerId(customerBO.getCustomerId());        //客户id
        creditRecord.setBankId(customerBO.getBankId());            //贷款银行id
        creditRecord.setBankName(customerBO.getBankName());              //贷款银行名称
        creditRecord.setQueryStatus(CreditStatusEnum.BE_ENTERED.getCode());  //征信状态
        creditRecord.setStaffId(logedUser.getStaffId());                      //发起征信查询申请的员工ID
        creditRecord.setStaffName(logedUser.getStaffName());                    //发起征信查询申请的员工姓名
        creditRecord.setDeptId(logedUser.getDeptId());                       //业务部门ID
        creditRecord.setDeptName(logedUser.getDeptName());                     //业务部门名称
        creditRecord.setAnnexBatchNo(customerBO.getAnnexBatchNo());                 //附件批次编号
        creditQueryApplyManager.insertSelective(creditRecord);
        log.info("新增客户征信信息完成...");
        /**3、新增订单与客户关联关系**/
        log.info("正在新增订单与客户关联关系信息...");
        OrderCustomerRelDO orderCusRelRecord = new OrderCustomerRelDO();
        orderCusRelRecord.setOrderNo(customerBO.getOrderNo());                               //订单号
        orderCusRelRecord.setCustomerId(customerBO.getCustomerId());                     //客户编号
        orderCusRelRecord.setCustomerType(customerBO.getCustomerType());                     //客户类型
        orderCusRelRecord.setCreditApplyId(creditRecord.getCreditQueryApplyId());            //征信申请编号
        orderCusRelRecord.setIsDeleted(IsDeletedEnum.NORMAL.getCode());                 //是否删除：未删除
        orderCustomerRelManager.insertSelective(orderCusRelRecord);
        log.info("新增订单与客户关联关系信息完成...");
    }


    /**
     * 审核前和审核后修改征信情况
     * @param orderNo
     * @throws SuzukiCommonException
     */
    public void updateStatusByOrder(String orderNo,User logedUser) throws SuzukiCommonException{
        /**根据状态去判断该订单是审核前还是审核后**/
        Boolean isApproved = applyService.isOrderStatusByApproved(orderNo);
        /**根据状态去判断征信结果是否录入完成**/
        Boolean isFlag = this.allowToApply(orderNo);
        if(isApproved){
            /**true为审核后**/
            if(isFlag){
                /**如果存在把订单状态改为"修改征信结果已录入"**/
                orderServiceImpl.changeOrderStatus(orderNo,OrderStatusEnum.UPDATE_HAS_BEEN_RECORDER.getCode());   //修改征信结果已录入
            }else {
                /**如果存在把订单状态改为"修改征信结果待录入"**/
                orderServiceImpl.changeOrderStatus(orderNo,OrderStatusEnum.UPDATE_CREDITING.getCode());   //修改征信结果待录入
            }
        }else {
            /**false为审核前**/
            if(isFlag){
                /**如果存在把订单状态改为"征信结果已录入"**/
                orderServiceImpl.changeOrderStatus(orderNo,OrderStatusEnum.CREDIT_HAS_BEEN_RECORDER.getCode());   //征信结果已录入
            }else {
                /**如果存在把订单状态改为"征信结果待录入"**/
                orderServiceImpl.changeOrderStatus(orderNo,OrderStatusEnum.CREDITING.getCode());    //征信结果待录入
            }
        }
    }


    /**
     * 根据订单号查询该订单下是否有未录入的征信
     * @param orderNo
     * @return
     * @throws SuzukiCommonException
     */
    public Boolean allowToApply(String orderNo) throws SuzukiCommonException {
     /**根据订单号查询征信**/
        log.info("开始查询订单：{}的征信信息...", orderNo);
        int status = creditQueryApplyExtMapper.queryByStatus(orderNo);
        if(status == 0){
            log.info("该订单存在未录入的征信报告...");
            return false;
        }else {
            log.info("该订单无未录入的征信报告...");
            return true;
        }

    }

}
